package com.github.tyc1210.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.github.tyc1210.common.DynamicDataSourceConstant;
import com.github.tyc1210.properties.DataSourceProperties;
import com.github.tyc1210.properties.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置所有数据源
 */
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig{
    @Autowired
    private DynamicDataSourceProperties properties;

//    @Bean
//    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
//    public DataSource dataSource1(){
//        // 底层会自动拿到 prefix 值下的配置（默认：spring.datasource.druid），创建一个 DruidDataSource
//        return DruidDataSourceBuilder.create().build();
//    }

    /**
     * 注入自定义数据源
     *  包含多个数据源以及默认数据源
     * @return
     */
    @Bean
    public DynamicDataSource dataSource(){
        // 底层会自动拿到 prefix 值下的配置（默认：spring.datasource.druid），创建一个 DruidDataSource
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> dataSourceMap = getDynamicDataSource();
        // 设置所有所有数据源
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        // 设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSourceMap.get(DynamicDataSourceConstant.DEFAULT_KEY));
        return dynamicDataSource;
    }

    private Map<Object,Object> getDynamicDataSource(){
        // 获取所有数据源配置
        Map<String, DataSourceProperties> dataSourcePropertiesMap = properties.getDataSource();
        Map<Object,Object> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
        dataSourcePropertiesMap.forEach((k,v)->{
            DruidDataSource dataSource = DynamicDataSourceFactory.buildDruidDataSource(v);
            targetDataSources.put(k,dataSource);
            DynamicContextHolder.putDataSource(k,dataSource);
        });
        return targetDataSources;
    }
}
